package com.cql.web.controller.business;

import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.MenuDTO;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.core.security.LoginUser;
import com.cql.framework.config.security.service.TokenService;
import com.cql.service.business.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cql
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private TokenService tokenService;

    /**
     * 创建菜谱
     *
     * @param request
     * @return
     */
    @PostMapping
    @PreAuthorize("@auth.hasRole('chef')")
    public AjaxResult createMenu(@Validated @RequestBody MenuDTO menu, HttpServletRequest request) {
        /**
         * 1.如果带有menuId，说明是修改
         */

        UserDO user = tokenService.getLoginUser(request).getUserDO();

        MenuDTO result = menuService.saveOrUpdate(menu, user);


        return AjaxResult.success("menu", result);
    }

    /**
     * 用于已登录用户查询自己的信息
     *
     * @param menuId
     * @param request
     * @return
     */
    @PreAuthorize("@auth.hasRole('chef')")
    @GetMapping("/{menuId}")
    public AjaxResult getMenu(@PathVariable("menuId") Long menuId, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        MenuDTO menu = menuService.getMenuById(menuId, loginUser.getUserDO().getUserId());

        return AjaxResult.success(menu);
    }


}
